package org.hyh.core.utils;

import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.hyh.core.Exception.TokenAuthenticationException;
import org.hyh.core.model.entity.SysUser;
import org.hyh.core.model.properties.JwtProperties;
import sun.rmi.runtime.Log;

import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @auther :hyh
 * @desc :        jwt的工具类。
 * @date :2020/7/12
 */
@Slf4j
public class JwtUtils {

    private final  static JwtProperties jwtProperties = SpringUtils.getBeanByClass(JwtProperties.class);

    public static   String   getToken(SysUser sysUser){
        JwtBuilder builder = Jwts.builder();
        //设置头部
        builder.setHeaderParam("type", "JWT");
        //设置算法签名和 salt
        builder.signWith(SignatureAlgorithm.HS256, jwtProperties.getSecretKey());

        long millis = System.currentTimeMillis();
        builder.setClaims(builderClaims(sysUser))
                //这里必须先设置claims ，在设置过期时间。否则过期时间会失效。
                .setIssuedAt(new Date(millis))
                .setIssuer(jwtProperties.getIssuer())
                .setAudience(jwtProperties.getAudience())
                .setSubject(sysUser.getNickname())
                .setExpiration(new Date(millis + jwtProperties.getExpiryMillis()));

        //设置体

        String token = builder.compact();
        log.info("------>当前用户：{}生成的token:{}",sysUser.getId(),token);
        return token;
    }

    private static Map<String, Object> builderClaims(SysUser sysUser) {
         Map<String,Object> map =new HashMap<>();
        map.putIfAbsent("userId", sysUser.getId());
        map.putIfAbsent("userName", sysUser.getUsername());


        return map;
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static SysUser parseToken (String token) {
        log.info("----->本次token:{}",token);
        JwtParser parser = Jwts.parser();
        try {
            parser.setSigningKey(jwtProperties.getSecretKey());
            Claims body = parser.parseClaimsJws(token).getBody();
            Date expiration = body.getExpiration();
            SysUser sysUser = new SysUser();
            sysUser.setUsername(body.get("userName", String.class));
            sysUser.setId(body.get("userId", String.class));
            return sysUser;
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
            throw new TokenAuthenticationException("访问令牌过期，请重新登录!");
        }





    }
}
